package com.molichuxing.services.aspect;

import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.services.property.IovTokenErrorCodeEnum;
import com.molichuxing.services.util.IovPropertyUtils;
import com.molichuxing.services.util.IovUtils;
import org.apache.xalan.templates.ElemAttributeSet;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author: liuruifeng
 * @create_date: 2019-10-12
 **/
@Component("iovTokenAspect")
@Aspect
public class IovTokenAspect {
	private static final Logger logger = LoggerFactory.getLogger(IovTokenAspect.class);

	@Resource
	private IovUtils tokenUtil;

	@Pointcut("execution(public * com.molichuxing.services.infrastructure.service.Iov*Service.*(..))")
	private void servicePointcut() {
	}

	@Around("servicePointcut()")
	public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
		String methodName = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
		Object obj = null;
		try {
			String token = tokenUtil.getSet();
			IovUtils.setTokenToHeader(token);

			obj = joinPoint.proceed();

			logger.info("执行车联网方法{}, 返回结果为:{}", methodName, obj);
			if (obj != null && obj instanceof ResponseResult) {
				ResponseResult result = (ResponseResult)obj;
				if (IovTokenErrorCodeEnum.getEnum(result.getCode()) != null) {
					token = tokenUtil.setGet();
					IovUtils.setTokenToHeader(token);
					obj = joinPoint.proceed();
				}
			}
		} catch (BizException e) {
			if (e.getExceptionCode() != null && IovTokenErrorCodeEnum.getEnum(e.getExceptionCode()) != null) {
				String token = tokenUtil.setGet();
				IovUtils.setTokenToHeader(token);
				obj = joinPoint.proceed();
			} else {
				throw e;
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new RuntimeException("服务提供者的服务实现AOP错误, 无法修复");
		}
		return obj;
	}
}
